<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexNormRequest;
use App\Http\Requests\StoreNormRequest;
use App\Http\Requests\UpdateNormRequest;
use App\Http\Resources\NormResource;
use App\Models\Norm;
use App\Models\NormKey;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class NormController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexNormRequest $request)
    {
        $query = Norm::query();
        if (!isSuperadmin()) {
            $query->where('admin_id', Auth::id());
        }

        $query->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where(function ($subquery) use ($name) {
                $subquery->where('name', 'like', "%$name%");
            });
        })->when($request->filled('status'), function ($query) use ($request) {
            return $query->where('status', $request->input('status'));
        });

        $data = $query->with(['normkeys', 'statuslabel'])->orderBy('order')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  NormResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreNormRequest $request, Norm $norm)
    {

        // 开启事务
        DB::beginTransaction();
        try {
            $norm->fill($request->input());
            $norm->admin_id = Auth::id();
            $norm->save();
            // 如果请求中包含 norm_keys 数据
            if ($request->filled('normkeys')) {
                foreach ($request->input('normkeys') as $keyValue) {
                    $normKey = new NormKey();
                    $normKey->key = $keyValue['key'];
                    $normKey->value = $keyValue['value'];
                    // 关联 norms 表
                    $normKey->norm_id = $norm->id;
                    $normKey->save();
                }
            }
            // 提交事务
            DB::commit();

            return $this->success('添加成功', $norm);
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('添加失败', $e);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Norm $norm)
    {
        $data = $norm->load(['normkeys', 'statuslabel']);
        return $this->success('查询成功', $data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Norm $norm)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateNormRequest $request, Norm $norm)
    {
        // 获取要更新的 norms 记录
        // $norm = Norm::findOrFail($id);
        $this->authorize('update', $norm);
        // 开启事务
        DB::beginTransaction();

        try {
            // 更新 norms 记录
            $norm->fill($request->all());
            $norm->save();

            // 如果请求中包含 normkeys 数据
            if ($request->filled('normkeys')) {
                // 删除原有的 normkeys 记录
                $norm->normkeys()->delete();

                // 创建新的 normkeys 记录
                foreach ($request->input('normkeys') as $keyValue) {
                    $normKey = new NormKey();
                    $normKey->key = $keyValue['key'];
                    $normKey->value = $keyValue['value'];
                    // 关联 norms 表
                    $normKey->norm_id = $norm->id;
                    $normKey->save();
                }
            }

            // 提交事务
            DB::commit();

            return $this->success('更新成功', $norm);
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('更新失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Norm $norm)
    {
        $this->authorize('delete', $norm);
        // 开启事务
        DB::beginTransaction();

        try {
            // 删除与当前 norms 记录相关联的 norm_keys 记录
            $norm->normkeys()->delete();
            // 删除 norms 记录
            $norm->delete();
            // 提交事务
            DB::commit();

            return $this->success('删除成功');
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('删除失败');
        }
    }
}
